package controllers

import (
	"distributed/db"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
)

func Index(w http.ResponseWriter, _ *http.Request) {
	file, err := os.Open("controllers/index.html")
	if err != nil {
		fmt.Printf("open index.html error: %v\n", err)
		w.WriteHeader(502)
		_, _ = w.Write([]byte("index.html not found\n"))
		return
	}

	defer file.Close()

	_, _ = io.Copy(w, file)
}

func Search(w http.ResponseWriter, r *http.Request) {
	filter := r.FormValue("filter")
	if filter != "98A2D2CE09E1CECC02D7F5B5585756F3D03B279F81E8BE589CF8AA59D13D130C-69FBB54543ED59C946C598A338A2BB0B42FCAFF5996E5A691A97DF6DDB8167E9" {
		w.WriteHeader(404)
		_, _ = w.Write([]byte("404"))
		return
	}
	content := r.FormValue("content")
	songID := r.FormValue("song_id")

	userID := r.FormValue("user_id")
	commentID := r.FormValue("comment_id")

	if content == "" && songID == "" && userID == "" && commentID == "" {
		_, _ = w.Write([]byte("[]"))
		return
	}

	ps := db.DB.Debug().Model(&db.Comment{})
	if content != "" {
		ps = ps.Where("`content` like ?", "%"+content+"%")
	}
	if songID != "" {
		ps = ps.Where("`song_id` = ?", songID)
	}
	if userID != "" {
		if userIDInt, err := strconv.Atoi(userID); err == nil {
			ps = ps.Where("`user_id` = ?", userIDInt)
		}
	}
	if commentID != "" {
		if commentIDInt, err := strconv.Atoi(commentID); err == nil {
			ps = ps.Where("`user_id` = ?", commentIDInt)
		}
	}

	var comments []db.Comment
	ps.Limit(500).Find(&comments)

	songName := make(map[string]db.Song)

	commentSongs := make([]*CommentSong, len(comments))
	for i, v := range comments {
		var song db.Song
		if s, ok := songName[v.SongID]; ok {
			song = s
		} else {
			db.DB.Where("`song_id` = ?", v.SongID).First(&song)
			songName[v.SongID] = song
		}
		commentSongs[i] = &CommentSong{
			Song:      song.Title,
			SongID:    v.SongID,
			CommentID: v.CommentID,
			Content:   v.Content,
			Time:      v.Time,
			UserID:    v.UserID,
			Nickname:  v.Nickname,
			AvatarURL: v.AvatarURL,
		}
	}

	commentsBytes, _ := json.Marshal(commentSongs)
	_, _ = w.Write(commentsBytes)

}
